package com.koron.css2.baseConfig.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.bean.UseMatrTemplateBean;
import com.koron.css2.baseConfig.bean.UseMatrTemplateListBean;
import com.koron.css2.baseConfig.mapper.UseMatrTemplateMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.util.Constant;
import com.koron.util.JsonUtils;
import com.koron.util.ValidationKey;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用料模板-添加
 *
 * @author 廖大富
 */
public class UseMatrTemplateAdd implements ServerInterface {

    private static Logger logger = LogManager.getLogger(UseMatrTemplateAdd.class);

    @Override
    @ValidationKey(clazz = UseMatrTemplateBean.class,method = "insert")
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        try {
            UseMatrTemplateMapper mapper = factory.getMapper(UseMatrTemplateMapper.class);
            UseMatrTemplateBean bean = JsonUtils.objectToPojo(req.getData(), UseMatrTemplateBean.class);

            // 校验字段重复
            if (mapper.check("template_name", bean.getTemplateName()) > 0) {
                return MessageBean.create(Constant.ILLEGAL_PARAMETER, "模板名称：" + bean.getTemplateName() + "的信息已存在。", void.class);
            }
            bean.setCreateInfo(userInfo);
            // 获取用料明细信息
            List<UseMatrTemplateListBean> useMatrTemplateList = bean.getUseMatrTemplateList();
            if (null == useMatrTemplateList || useMatrTemplateList.size() == 0) {
                return MessageBean.create(Constant.ILLEGAL_PARAMETER, "模板明细不能为空！", void.class);
            }
            // 判断名称是否重复
            Set<String> set = new HashSet<>();
            for (UseMatrTemplateListBean useMatrTemplateListBean : useMatrTemplateList) {
                if (!set.add(useMatrTemplateListBean.getMatrName())) {
                    return MessageBean.create(Constant.ILLEGAL_PARAMETER, "材料名称：" + useMatrTemplateListBean.getMatrName() + "的信息重复。", void.class);
                }
                useMatrTemplateListBean.setTemplateId(bean.getId());
                useMatrTemplateListBean.setCreateInfo(userInfo);
            }
            mapper.insertUseMatrTemplate(bean);
            mapper.insertUseMatrTemplateList(useMatrTemplateList);
        } catch (Exception e) {
            logger.error("用料模板添加失败", e);
            factory.close(false);
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "用料模板添加失败", void.class);
        }
        return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", void.class);
    }

}